<template>
  <div class="setUser">
    <el-drawer title="我是标题" :visible.sync="drawerVisible" size="40%" :with-header="false" @close="cancelForm">
      <div class="drawerForm">
        <div class="pageTitle">
          <span class="titleBorder">|</span>
          <div class="titleText">{{ titleName }}</div>
          <slot name="header" />
          <el-divider />
        </div>
        <el-form
          ref="userData"
          :model="userData"
          :rules="rules"
          label-width="140px"
          style="flex: 1; margin: 0px 30px"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="用户姓名：" prop="userName">
                <el-input
                  v-model="userData.userName"
                  placeholder="请输入用户姓名"
                  maxlength="50"
                  show-word-limit
                  class="show-word-limit"
                />
              </el-form-item>
              <el-form-item ref="department" label="归属部门：" prop="department">
                <el-cascader
                  v-model="userData.department"
                  :options="departmentOptions"
                  :show-all-levels="false"
                  :props="{ checkStrictly: true }"
                  clearable
                  style="width: 100%"
                  @change="departmentChange"
                />
              </el-form-item>
              <el-form-item label="手机号码：" prop="mobileTel">
                <el-input v-model="userData.mobileTel" placeholder="请输入移动电话号码" type="tel" />
              </el-form-item>
              <el-form-item label="性别：">
                <el-radio v-model="userData.sex" label="男">男</el-radio>
                <el-radio v-model="userData.sex" label="女">女</el-radio>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="登录账号：" prop="loginName">
                <el-input
                  v-model="userData.loginName"
                  maxlength="50"
                  show-word-limit
                  placeholder="请输入登录账号"
                  class="show-word-limit"
                />
              </el-form-item>
              <el-form-item label="邮箱地址：" prop="email">
                <el-input
                  v-model="userData.email"
                  maxlength="50"
                  class="show-word-limit"
                  show-word-limit
                  placeholder="请输入邮箱地址"
                />
              </el-form-item>
              <el-form-item label="固定电话：" prop="telephone">
                <el-input
                  v-model="userData.telephone"
                  maxlength="20"
                  show-word-limit
                  placeholder="请输入固定电话号码"
                  class="show-word-limit"
                />
              </el-form-item>
              <el-form-item label="工号：" prop="jobCode">
                <el-input
                  v-model="userData.jobCode"
                  placeholder="请输入工号"
                  maxlength="50"
                  show-word-limit
                  class="show-word-limit"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="岗位人员授权书：" style="width: 50%">
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              accept=".pdf"
              :on-remove="postAuthorizationRemove"
              :before-remove="beforeRemove"
              :on-success="postAuthorizationSuccess"
              :on-preview="clickFileList"
              :limit="1"
              :file-list="userData.postAuthorization"
            >
              <el-button size="small" plain>
                点击上传
                <i class="el-icon-upload el-icon--right" />
              </el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="培训履历书：" style="width: 50%">
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              accept=".pdf"
              :on-remove="trainingResumeRemove"
              :before-remove="beforeRemove"
              :on-success="trainingResumeSuccess"
              :on-preview="clickFileList"
              :limit="1"
              :file-list="userData.trainingResume"
            >
              <el-button size="small" plain>
                点击上传
                <i class="el-icon-upload el-icon--right" />
              </el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="上岗证：" style="width: 50%">
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              accept=".pdf"
              :on-remove="workLicenseRemove"
              :before-remove="beforeRemove"
              :on-success="workLicenseSuccess"
              :on-preview="clickFileList"
              :limit="1"
              :file-list="userData.workLicense"
            >
              <el-button size="small" plain>
                点击上传
                <i class="el-icon-upload el-icon--right" />
              </el-button>
            </el-upload>
          </el-form-item>
          <el-form-item v-if="pageType === 'add'" label="新密码告知方式：" style="width: 50%">
            <el-select v-model="newPasswordInform" placeholder="请选择">
              <el-option v-for="item in InformOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-form>
        <div class="drawerFooter" align="right">
          <el-button @click="cancelForm">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { getDeptOptions } from '@/api/system-management'
import { ValidPhone } from '@/utils/validate'
import md5 from 'js-md5'
const { randomString } = require('@/utils')

const validPhone = (rule, value, callback) => {
  if (value && !ValidPhone(value)) {
    callback(new Error('请输入正确的11位手机号码'))
  } else {
    callback()
  }
}
export default {
  name: 'SetUser',
  components: {},
  data() {
    return {
      drawerVisible: false,
      uploadUrl: process.env.VUE_APP_BASE_API + 'vue/files/upload',
      pageType: '',
      detailType: 'index',
      titleName: '用户',
      newPasswordInform: 'self',
      InformOptions: [
        {
          value: 'self',
          label: '自行告知用户'
        },
        {
          value: 'email',
          label: '通过邮箱发送'
        }
      ],
      userData: {
        userId: null,
        userName: '',
        loginName: '',
        department: [],
        roleId: null,
        sex: '未定义',
        email: '',
        mobileTel: null,
        telephone: null,
        postAuthorization: [],
        trainingResume: [],
        workLicense: []
      },
      rules: {
        userName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        loginName: [{ required: true, message: '请输入登录账号', trigger: 'blur' }],
        department: [
          {
            required: true,
            type: 'array',
            message: '请选择部门',
            trigger: 'blur'
          }
        ],
        mobileTel: [{ validator: validPhone, trigger: 'blur' }]
      },
      departmentOptions: []
    }
  },
  mounted() {
    getDeptOptions().then((res) => {
      this.departmentOptions = this.parseJson(res.data)
    })
  },
  methods: {
    is(type, currentRow) {
      this.pageType = type
      this.drawerVisible = true

      if (type === 'add') {
        this.titleName = '新增用户'
      } else {
        this.titleName = '编辑用户'
        // this.$nextTick(() => {
        this.userData = JSON.parse(JSON.stringify(currentRow))
        this.userData.roleId = null
        // })
      }
    },
    // 递归把对象id换成value
    parseJson(arr) {
      if (arr.length === 0) {
        return []
      }
      arr = arr.slice()
      const key = 'value'
      function toParse(arr) {
        arr.forEach(function (item) {
          item[key] = item.id
          if (item.children && Array.isArray(item.children)) {
            toParse(item.children)
          }
          delete item.id
        })
        arr.forEach(function (item) {
          if (item.children && Array.isArray(item.children)) {
            if (item.children.length === 0) {
              delete item.children
            }
          }
        })
        return arr
      }
      return toParse(arr)
    },
    // 部门选择回调函数
    departmentChange() {
      if (this.userData.department.length > 0) {
        this.$refs.department.clearValidate()
      }
    },
    // 提交表单
    submitForm() {
      this.$refs['userData'].validate((valid) => {
        if (valid) {
          let originalPassword = ''
          if (this.pageType === 'add') {
            originalPassword = randomString(8)
            this.userData['password'] = md5(originalPassword)
          }

          this.$emit('submitForm', this.pageType, this.userData, this.newPasswordInform, originalPassword)
          // this.$emit('personSubmit', this.personData, this.type)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    // 取消表单
    cancelForm() {
      this.pageType = ''
      this.$emit('closeForm')
      this.drawerVisible = false
    },
    // 以下都是文件上传函数
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    postAuthorizationRemove(file, fileList) {
      this.userData.postAuthorization.splice(0, 1)
    },
    postAuthorizationSuccess(res, file) {
      this.userData.postAuthorization.push(res)
    },
    trainingResumeRemove(file, fileList) {
      this.userData.trainingResume.splice(0, 1)
    },
    trainingResumeSuccess(res, file) {
      this.userData.trainingResume.push(res)
    },
    workLicenseRemove(file, fileList) {
      this.userData.workLicense.splice(0, 1)
    },
    workLicenseSuccess(res, file) {
      this.userData.workLicense.push(res)
    },
    clickFileList(file) {
      window.open(process.env.VUE_APP_BASE_API + file.url)
    }
  }
}
</script>
<style lang="less">
.userRoleSelect {
  .el-select-menu__list {
    border-top: solid 1px #e4e7ed;
    padding: 10px;
    color: #606266;
    font-size: 14px;
    cursor: pointer;
    .nodeText {
      font-size: 14px;
    }
  }
  .el-select-menu__list:hover {
    background-color: #f5f7fa;
  }
}
</style>
<style lang="less" scoped>
.setUser {
  height: 100%;
  /deep/label {
    font-weight: 500;
  }
  .drawerForm {
    display: flex;
    flex-direction: column;
    height: 100%;
  }
  .drawerFooter {
    justify-content: right;
    padding: 20px;
  }
  .pageTitle {
    padding-top: 15px;
    padding-left: 15px;
    font-size: 20px;
    .titleBorder {
      font-weight: bold;
      font-size: 22px;
      color: #00a0e9;
      margin-right: 5px;
    }
    .titleText {
      display: inline;
      padding-right: 20px;
      padding-left: 5px;
    }
  }
}
</style>
